package com.slz3.business.redis;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.ArrayList;
import java.util.List;

public final class RedisLuaUtils {

    /**
     * 执行redis-lua脚本
     * @param redisTemplate     redis连接
     * @param scriptClassPath   脚本路径
     * @param keys              redis-lua接收keys参数值
     * @param args              redis-lua接收的args参数值
     * @param resultType        redis-lua返回类型
     */
    public static <T> T runScript(RedisTemplate redisTemplate, String scriptClassPath,
                           List<String> keys, Object[] args, Class<T> resultType){
        if (keys == null){
            keys = new ArrayList<>();
        }
        if (args == null){
            args = new Object[]{};
        }
        DefaultRedisScript<T> script = new DefaultRedisScript<>();
        ClassPathResource resource = new ClassPathResource(scriptClassPath);
        script.setScriptSource(new ResourceScriptSource(resource));
        script.setResultType(resultType);
        return (T) redisTemplate.execute(script, keys, args);
    }

    /**
     * 执行redis-lua脚本
     * @param redisTemplate         redis连接
     * @param scriptClassPath       脚本路径
     * @param resultType            redis-lua返回类型
     */
    public static <T> T runScript(RedisTemplate redisTemplate, String scriptClassPath, Class<T> resultType){
        return runScript(redisTemplate, scriptClassPath, null, null, resultType);
    }

    /**
     * 执行redis-lua脚本
     * @param redisTemplate         redis连接
     * @param scriptClassPath       脚本路径
     * @param keys                  redis-lua接收keys参数值
     * @param resultType            redis-lua返回类型
     */
    public static <T> T runScript(RedisTemplate redisTemplate, String scriptClassPath, List<String> keys, Class<T> resultType){
        return runScript(redisTemplate, scriptClassPath, keys, null, resultType);
    }

    /**
     * 执行redis-lua脚本
     * @param redisTemplate         redis连接
     * @param scriptClassPath       脚本路径
     * @param args                  redis-lua接收的args参数值
     * @param resultType            redis-lua返回类型
     */
    public static <T> T runScript(RedisTemplate redisTemplate, String scriptClassPath, Object[] args, Class<T> resultType){
        return runScript(redisTemplate, scriptClassPath, null, args, resultType);
    }
}
